import { CommonService } from '../../../../core/common/common.service';
import { ProductService } from '../../service/product.service';
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.scss']
})
export class ProductComponent implements OnInit {
  public products: Array<any>;
  public discnts: Array<any>;
  public selectedProduct: any = {};
  constructor(private route: ActivatedRoute, private router: Router, private common: CommonService,
    private productService: ProductService) {
    this.initProduct();
  }

  ngOnInit() {

  }
  private initProduct(): void {
    this.productService.getProducts().subscribe((data: any) => {
      this.products = data;
      this.selectedProduct = data.length > 0 ? data[0] : this.selectedProduct;
      this.selectedProduct.active = true;
      this.productSelected(this.selectedProduct);
    });
  }
  public productSelected(product: any): void {
    product.active = true;
    this.products.forEach((p: any) => {
      if (p.prodId === product.prodId) {
        p.active = true;
      } else {
        p.active = false;
      }
    });
    this.selectedProduct = product;
    this.productService.getDiscntByProd(product.prodId).subscribe((data: any) => {
      if (data) {
        data.forEach((d: any) => {
          let explanation = '';
          d.compCount = d.compCount || [];
          for (let i = 0; i < d.compCount.length; i++) {
            const n = d.compCount[i];
            if (i === d.compCount.length - 1) {
              explanation += n.bandWidth + 'M节点' + n.count + '个。 ';
            } else {
              explanation += n.bandWidth + 'M节点' + n.count + '个， ';
            }
          }
          d.explanation = explanation;
        });
      }
      this.discnts = data;
    });
  }
  public selectDiscnt(discnt: any): void {
    this.router.navigate(['/crm/sale', {
      'discnt': JSON.stringify(discnt),
      'product': JSON.stringify(this.selectedProduct),
      'backURL': this.common.getCurrentURL(this.route)
    }], { relativeTo: this.route.parent, skipLocationChange: true });
  }
}
